package com.ssy.lingxi.marketing.serviceimpl.component.coupon;

import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.marketing.model.constant.MarketingConstants;
import com.ssy.lingxi.marketing.utils.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 优惠券缓存服务实现类
 * @author ds, yzc
 * @version 2.0.0
 * @date 2021/8/19
 */
@Slf4j
@Service
public class CouponCacheComponent {

    @Resource
    private IRedisStringUtils stringUtils;


    /**
     * coupon_qt_ob:bt:{}:id:{} - num
     * 保持和#incrCouponObtainQuantity方法的下标一致
     */

    public Integer getCouponObtainQuantity(BelongTypeEnum belongTypeEnum, Long couponId) {
        String key = StrUtil.format(MarketingConstants.coupon_quantity_key_template, belongTypeEnum.getCode(), couponId);
        String value = stringUtils.getCouponQuantityScript(key);
        if (!StringUtils.hasLength(value)) {
            return 0;
        }
        return Integer.valueOf(value);
    }

    /**
     *
     * 增加发券数量
     * @param belongTypeEnum 所属类型
     * @param couponId 优惠券id
     */
    public Integer incrCouponObtainQuantity(BelongTypeEnum belongTypeEnum, Long couponId, Integer quantity) {
        String key = StrUtil.format(MarketingConstants.coupon_quantity_key_template, belongTypeEnum.getCode(), couponId);
        String result = stringUtils.executeCouponQuantityScript(key, quantity);
        if (Objects.isNull(result) || Integer.parseInt(result) < 0) {
            return null;
        }

        return Integer.valueOf(result);
    }

    /**
     * 生成平台优惠券编码
     * @param id 平台优惠券id
     * @return 返回结果
     */
    public String generatePlatformCouponCode(Long id) {
        return "PYH" + CodeUtils.digits32(id, 6);
    }

    /**
     * 生成商家优惠券编码
     * @param id 商家优惠券id
     * @return 返回结果
     */
    public String generateMerchantCouponCode(Long id) {
        return "MYH" + CodeUtils.digits32(id, 6);
    }
}
